using Live.Core.Douyin;
using System;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;

namespace TangLiveRecorder.Services
{
    /// <summary>
    /// 轮询服务 - 定期执行任务并打印日志
    /// </summary>
    public class PollingService
    {
        private System.Threading.Timer _timer;
        private readonly int _intervalSeconds;
        private bool _isRunning;
        private readonly object _lockObject = new object();
        private readonly RecordingService _recordingService;

        public PollingService(int intervalSeconds = 10, RecordingService recordingService = null)
        {
            _intervalSeconds = intervalSeconds;
            _isRunning = false;
            _recordingService = recordingService;
        }

        /// <summary>
        /// 启动轮询服务
        /// </summary>
        public void Start()
        {
            lock (_lockObject)
            {
                if (_isRunning)
                {
                    Data.AddLog("轮询服务已经在运行中");
                    return;
                }

                _timer = new System.Threading.Timer(ExecutePolling, null, TimeSpan.Zero, TimeSpan.FromSeconds(_intervalSeconds));
                _isRunning = true;
                Data.AddLog($"轮询服务已启动，间隔: {_intervalSeconds}秒");
            }
        }

        /// <summary>
        /// 停止轮询服务
        /// </summary>
        public void Stop()
        {
            lock (_lockObject)
            {
                if (!_isRunning)
                {
                    Data.AddLog("轮询服务未在运行");
                    return;
                }

                _timer?.Dispose();
                _timer = null;
                _isRunning = false;
                Data.AddLog("轮询服务已停止");
            }
        }

        /// <summary>
        /// 执行轮询任务
        /// </summary>
        /// <param name="state">状态对象</param>
        private void ExecutePolling(object state)
        {
            try
            {
                var currentTime = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
                Data.AddLog($"[轮询服务] 执行定时任务 - {currentTime}");

                // 这里可以添加具体的轮询逻辑
                // 例如：检查直播状态、清理临时文件、监控系统资源等
                PerformPollingTasks();
            }
            catch (Exception ex)
            {
                Data.AddLog($"[轮询服务] 执行任务时发生错误: {ex.Message}");
            }
        }

        /// <summary>
        /// 执行具体的轮询任务
        /// </summary>
        private void PerformPollingTasks()
        {
            // 检查系统状态
            CheckSystemStatus();

            // 监控直播状态
            MonitorLiveStatus();
        }

        /// <summary>
        /// 检查系统状态
        /// </summary>
        private void CheckSystemStatus()
        {
            var memoryUsage = GC.GetTotalMemory(false) / 1024 / 1024; // MB
            Data.AddLog($"[轮询服务] 系统内存使用: {memoryUsage} MB");
        }

        /// <summary>
        /// 监控直播状态
        /// </summary>
        private async Task MonitorLiveStatus()
        {
            var allLives = Data.GetAllLives();
            if (allLives?.Count > 0)
            {
                foreach (var live in allLives)
                {
                    // 如果直播间被禁用，设置为非直播状态
                    if (!live.Status)
                    {
                        live.IsLive = false;
                        live.IsRecording = false; // 禁用时停止录制
                        Data.UpdateLive(live, false);
                        continue;
                    }

                    // 获取直播流数据
                    var streamData = await DouyinRoom.GetDouyinStreamData(live.Url, null, Data.AddLog);

                    if (streamData != null && streamData.IsLive)
                    {
                        // 主播正在直播
                        live.Name = streamData.AnchorName;
                        live.IsLive = true;

                        // 检查录制状态
                        if (!live.IsRecording)
                        {
                            // 启动录制逻辑
                            StartRecording(live, streamData);
                            live.IsRecording = true;
                            Data.AddLog($"[轮询服务] {streamData.AnchorName}正在直播，开始录制");
                        }
                        else
                        {
                            Data.AddLog($"[轮询服务] {streamData.AnchorName}正在直播，录制中...");
                        }

                        Data.UpdateLive(live);
                    }
                    else
                    {
                        // 主播未在直播
                        bool wasLive = live.IsLive;
                        live.IsLive = false;

                        // 如果之前在录制，停止录制
                        if (live.IsRecording)
                        {
                            // 停止录制逻辑
                            StopRecording(live);
                            live.IsRecording = false;
                            Data.AddLog($"[轮询服务] {live.Name}已下播，停止录制");
                        }

                        Data.UpdateLive(live, false);

                        if (wasLive)
                        {
                            Data.AddLog($"[轮询服务] {live.Name}已下播");
                        }
                    }
                }
            }
            var liveCount = allLives?.Count ?? 0;
            var recordingCount = allLives?.Count(l => l.IsRecording) ?? 0;
            Data.AddLog($"[轮询服务] 当前监控直播数量: {liveCount}，正在录制: {recordingCount}");
        }

        /// <summary>
        /// 获取服务运行状态
        /// </summary>
        /// <returns>是否正在运行</returns>
        public bool IsRunning => _isRunning;

        /// <summary>
        /// 手动执行一次轮询
        /// </summary>
        public void ExecuteOnce()
        {
            Data.AddLog("[轮询服务] 手动触发轮询执行");
            ExecutePolling(null);
        }

        /// <summary>
        /// 更新轮询间隔
        /// </summary>
        /// <param name="newIntervalSeconds">新的间隔秒数</param>
        public void UpdateInterval(int newIntervalSeconds)
        {
            if (_isRunning)
            {
                Stop();
                System.Threading.Thread.Sleep(100); // 短暂等待确保停止
                var oldService = new PollingService(newIntervalSeconds);
                oldService.Start();
                Data.AddLog($"[轮询服务] 间隔已更新为: {newIntervalSeconds}秒");
            }
        }

        /// <summary>
        /// 启动录制
        /// </summary>
        /// <param name="live">直播信息</param>
        /// <param name="streamData">直播流数据</param>
        private async void StartRecording(Models.LiveInfo live, DouyinStreamResult streamData)
        {
            try
            {
                if (_recordingService != null)
                {
                    // 优先使用StreamUrl，如果没有则使用M3u8Url
                    var streamUrl = !string.IsNullOrEmpty(streamData?.StreamUrl) ? streamData.StreamUrl : streamData?.M3u8Url;

                    if (!string.IsNullOrEmpty(streamUrl))
                    {
                        var success = await _recordingService.StartRecordingAsync(live, streamUrl);
                        if (!success)
                        {
                            live.IsRecording = false;
                            Data.AddLog($"[录制服务] 启动录制失败: {live.Name}");
                        }
                    }
                    else
                    {
                        Data.AddLog($"[录制服务] 流地址无效: {live.Name}");
                        live.IsRecording = false;
                    }
                }
                else
                {
                    Data.AddLog($"[录制服务] 录制服务未初始化: {live.Name}");
                    live.IsRecording = false;
                }
            }
            catch (Exception ex)
            {
                Data.AddLog($"[录制服务] 启动录制异常: {ex.Message}");
                live.IsRecording = false;
            }
        }

        /// <summary>
        /// 停止录制
        /// </summary>
        /// <param name="live">直播信息</param>
        private async void StopRecording(Models.LiveInfo live)
        {
            try
            {
                if (_recordingService != null)
                {
                    var success = await _recordingService.StopRecordingAsync(live.Guid);
                    if (!success)
                    {
                        Data.AddLog($"[录制服务] 停止录制失败: {live.Name}");
                    }
                }
                else
                {
                    Data.AddLog($"[录制服务] 录制服务未初始化: {live.Name}");
                }
            }
            catch (Exception ex)
            {
                Data.AddLog($"[录制服务] 停止录制异常: {ex.Message}");
            }
        }

        /// <summary>
        /// 获取当前录制状态统计
        /// </summary>
        /// <returns>录制状态信息</returns>
        public (int TotalLives, int LiveCount, int RecordingCount) GetRecordingStatus()
        {
            var allLives = Data.GetAllLives();
            if (allLives == null)
                return (0, 0, 0);

            var totalLives = allLives.Count;
            var liveCount = allLives.Count(l => l.IsLive);
            var recordingCount = allLives.Count(l => l.IsRecording);

            return (totalLives, liveCount, recordingCount);
        }

        /// <summary>
        /// 释放资源
        /// </summary>
        public void Dispose()
        {
            Stop();
        }
    }
}